<template>
    <Contextmenu
        ref="contextMenuRef"
        :width="180"
        :items="currentMenuItems"
        @contextmenuItemClick="onMenuItemClick"
    />
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import Contextmenu from '/@/components/contextmenu/index.vue'
import type { ContextMenuItem, ContextmenuItemClickEmitArg } from '/@/components/contextmenu/interface'
import { ElMessage } from 'element-plus'

interface RowContextMenuItem extends ContextMenuItem {
    rowAction?: string
}

interface Props {
    defaultItems?: RowContextMenuItem[]
    showView?: boolean
    showEdit?: boolean
    showDelete?: boolean
}

const props = withDefaults(defineProps<Props>(), {
    defaultItems: () => [],
    showView: true,
    showEdit: true,
    showDelete: true
})

const emit = defineEmits(['menu-item-click'])

const contextMenuRef = ref<any>(null)
const currentRow = ref<Record<string, any>>({})

// 默认菜单项
const defaultMenuItems = computed(() => {
    const items: RowContextMenuItem[] = []

    if (props.showView) {
        items.push({
            name: 'view',
            label: '查看详情',
            icon: 'el-icon-view',
            rowAction: 'view'
        })
    }

    if (props.showEdit) {
        items.push({
            name: 'edit',
            label: '编辑',
            icon: 'el-icon-edit',
            rowAction: 'edit'
        })
    }

    if (props.showDelete) {
        items.push({
            name: 'delete',
            label: '删除',
            icon: 'el-icon-delete',
            rowAction: 'delete'
        })
    }

    return items
})

// 合并默认菜单项和自定义菜单项
const currentMenuItems = computed(() => {
    return [...defaultMenuItems.value, ...props.defaultItems]
})

// 处理菜单项点击
const onMenuItemClick = (item: ContextmenuItemClickEmitArg) => {
    emit('menu-item-click', { item, row: currentRow.value })
}

// 显示上下文菜单
const showContextMenu = (e: MouseEvent, row: Record<string, any>) => {
    if (!contextMenuRef.value) return
    
    e.preventDefault()
    currentRow.value = row
    
    // 直接传递鼠标事件坐标，不添加任何偏移
    contextMenuRef.value.onShowContextmenu(
        {},
        {
            x: e.clientX,
            y: e.clientY
        }
    )
}

defineExpose({
    showContextMenu
})
</script>